package beikai.com.assistant.service.impl;

import beikai.com.assistant.common.domain.dto.UserDto;
import beikai.com.assistant.common.domain.params.UserParams;
import beikai.com.assistant.common.util.R;
import beikai.com.assistant.dao.mapper.UserMapper;
import beikai.com.assistant.dao.model.UserModel;
import beikai.com.assistant.service.IUserService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import lombok.SneakyThrows;
import org.apache.ibatis.javassist.NotFoundException;
import org.springframework.stereotype.Service;

import java.util.Objects;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author beikai
 * @since 2021-12-19
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserModel> implements IUserService {

    @SneakyThrows
    @Override
    public JSONObject login(UserParams params) {
        UserModel one = getOne(Wrappers.lambdaQuery(new UserModel())
                .eq(UserModel::getUsername, params.getUsername())
                .eq(UserModel::getPassword, params.getPassword())
                .eq(UserModel::getIsDelete, false)
                .last("limit 1")
        );
        if (Objects.isNull(one)) {
            throw new NotFoundException("用户未发现!");
        }
        UserDto build = UserDto.builder()
                .userId(one.getId())
                .username(one.getUsername())
                .build();
        return R.success(build);
    }

    @Override
    public JSONObject register(UserParams params) {
        UserModel userModel = new UserModel();
        userModel.setUsername(params.getUsername());
        userModel.setPassword(params.getPassword());
        return R.success(save(userModel));
    }

    @Override
    public JSONObject list(UserParams params) {
        IPage<UserModel> page = page(new Page<>(params.getPageNum(), params.getPageSize()),
                Wrappers.lambdaQuery(new UserModel())
                        .eq(UserModel::getIsDelete, false)
                        .like(!Strings.isNullOrEmpty(params.getUsername()), UserModel::getUsername, params.getUsername())
                        .eq(!Strings.isNullOrEmpty(params.getPassword()), UserModel::getPassword, params.getPassword())
        );
        return R.successPage(page.getPages(),page.getTotal(),page.getRecords());
    }
}
